package com.hanbang.gycatering.shoppingcart;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.aboutme.AboutMe;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.RelatedData;
import com.hanbang.gycatering.bean.ShoppingCartData;
import com.hanbang.gycatering.classify.ClassifyActivity;
import com.hanbang.gycatering.classify.ProductDetail;
import com.hanbang.gycatering.homepage.MainBaseActivity;
import com.hanbang.gycatering.homepage.HomePageActivity;
import com.hanbang.gycatering.myviews.HorizontalListView;
import com.hanbang.gycatering.myviews.ListViewForScrollView;
import com.hanbang.gycatering.myviews.MyDialog;
import com.hanbang.gycatering.myviews.MyDialog.MODE;
import com.hanbang.gycatering.myviews.MyDialog.OnClickCallback;
import com.hanbang.gycatering.myviews.NumberSelectView;
import com.hanbang.gycatering.myviews.NumberSelectView.OnItemClickListener;
import com.hanbang.gycatering.property.PropertyService;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.JsonHelper;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MySharedPreferences;
import com.hanbang.gycatering.utils.ShareMethod;
import com.hanbang.gycatering.utils.SystemTools;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class ShoppingCart extends MainBaseActivity {
	private ViewGroup ll_one, ll_two, ll_three, ll_four, ll_five;

	private PullToRefreshScrollView scrollView;

	private ListViewForScrollView listViewForScrollView;
	private MyAdapterVertical verticalAdapter = null;
	private ArrayList<ShoppingCartData> verticalListData = new ArrayList<ShoppingCartData>();
	private HorizontalListView horizontalListView;
	private ArrayList<RelatedData> horizontalListDara = new ArrayList<RelatedData>();
	private MyAdapterHorizontal horizontalAdapter = null;
	private TextView editTextView;
	private Button allSelectButton = null;
	private LinearLayout tab1 = null;
	private RelativeLayout tab2 = null;
	private boolean isDeleteMode = false;
	// 被选中的个数
	private int selectCount = 0;
	// 总计多少钱
	private double countMoney = 0;
	// 选中的商品的数量
	private int goodCount = 0;

	private TextView countTextView = null;
	private TextView countMoneyTextView = null;
	private TextView delete;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initAnim();
		setContentView(R.layout.shoppingcart);
		initView();
		setTheClick();
	}

	private void initView() {
		((TextView) findViewById(R.id.top_bar_title)).setText("购物车");
		((ImageView) findViewById(R.id.top_bar_left_image))
				.setVisibility(View.GONE);
		ll_one = (ViewGroup) findViewById(R.id.bottom_bar_ll1);
		ll_two = (ViewGroup) findViewById(R.id.bottom_bar_ll2);
		ll_three = (ViewGroup) findViewById(R.id.bottom_bar_ll3);
		ll_four = (ViewGroup) findViewById(R.id.bottom_bar_ll4);
		ll_five = (ViewGroup) findViewById(R.id.bottom_bar_ll5);
		listViewForScrollView = (ListViewForScrollView) findViewById(R.id.listview);
		verticalAdapter = new MyAdapterVertical();
		listViewForScrollView.setAdapter(verticalAdapter);

		horizontalListView = (HorizontalListView) findViewById(R.id.listview2);
		horizontalAdapter = new MyAdapterHorizontal();
		horizontalListView.setAdapter(horizontalAdapter);
		horizontalListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent intent = new Intent(ShoppingCart.this,
								ProductDetail.class);
						intent.putExtra("id", horizontalListDara.get(position)
								.getGoodsid());
						startActivity(intent);

					}
				});
		editTextView = (TextView) findViewById(R.id.right_text);
		editTextView.setVisibility(View.VISIBLE);
		editTextView.setText("编辑");
		isDeleteMode = false;
		editTextView.setOnClickListener(myOncClickListener);
		countTextView = (TextView) findViewById(R.id.count);
		countMoneyTextView = (TextView) findViewById(R.id.money);
		tab1 = (LinearLayout) findViewById(R.id.tab1);
		tab2 = (RelativeLayout) findViewById(R.id.tab2);
		allSelectButton = (Button) tab1.findViewById(R.id.all);
		delete = (TextView) findViewById(R.id.delete);
		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);

		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.getHeaderLayout().setBackgroundColor(
				getResources().getColor(R.color.gray_e8));
	}

	private void setTheClick() {
		ll_one.setOnClickListener(myOncClickListener);
		ll_two.setOnClickListener(myOncClickListener);
		ll_three.setOnClickListener(myOncClickListener);
		ll_four.setOnClickListener(myOncClickListener);
		ll_five.setOnClickListener(myOncClickListener);
		allSelectButton.setOnClickListener(myOncClickListener);
		delete.setOnClickListener(myOncClickListener);

		scrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				getCartlist();

			}
		});
	}

	private OnClickListener myOncClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			Intent intent = new Intent();
			switch (view.getId()) {
			case R.id.bottom_bar_ll1:
				intent.setClass(ShoppingCart.this, HomePageActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll3:
				intent.setClass(ShoppingCart.this, PropertyService.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll2:
				intent.setClass(ShoppingCart.this, ClassifyActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll5:
				intent.setClass(ShoppingCart.this, AboutMe.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.all:
				allSelectButton.setSelected(!allSelectButton.isSelected());
				boolean isSelected = allSelectButton.isSelected();
				selete(isSelected);
				verticalAdapter.notifyDataSetChanged();
				break;
			case R.id.right_text:
				if (isDeleteMode) {
					isDeleteMode = false;
					allSelectButton = (Button) tab1.findViewById(R.id.all);
					allSelectButton.setOnClickListener(myOncClickListener);
					allSelectButton.setSelected(true);
					selete(true);
					editTextView.setText("编辑");
					verticalAdapter.notifyDataSetChanged();
				} else {
					isDeleteMode = true;
					allSelectButton = (Button) tab2.findViewById(R.id.all);
					allSelectButton.setOnClickListener(myOncClickListener);

					selete(false);
					editTextView.setText("完成");
					verticalAdapter.notifyDataSetChanged();
				}
				setAnim();
				break;
			case R.id.delete:
				if (isDeleteMode) {
					if (selectCount <= 0) {
						MyDialog dialog = new MyDialog(ShoppingCart.this,
								R.style.base_dialog, MODE.HINT);
						dialog.setTitle("友情提示");
						dialog.setContent("请先选择商品");
						dialog.show();
						break;
					}
					// 确认提示
					MyDialog dialog = new MyDialog(ShoppingCart.this,
							R.style.base_dialog, MODE.CONFIRM);
					dialog.setTitle("删除确认");
					dialog.setQuxiao("暂不删除");
					dialog.setContent("是否确认删除" + goodCount + "件商品？");
					dialog.setConfirm("确认删除");
					dialog.setOnClickCallback(new OnClickCallback() {
						@Override
						public void onClick(MyDialog dialog, Object number,
								Object content) {
							if (((Integer) number) == 2) {
								delete();
							}

						}
					});
					dialog.show();
				}
				break;
			default:
				break;
			}
		}
	};

	private Animation showAction = null, hiddenAction = null;

	private void initAnim() {
		showAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		showAction.setDuration(150);
		hiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
		hiddenAction.setDuration(150);
	}

	/*
	 * is == true 显示tab1
	 */
	private void setAnim() {

		tab1.clearAnimation();
		tab2.clearAnimation();
		hiddenAction.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				if (!isDeleteMode) {
					tab2.setVisibility(View.GONE);
					tab1.setVisibility(View.VISIBLE);
					tab1.startAnimation(showAction);
				} else {
					tab1.setVisibility(View.GONE);
					tab2.setVisibility(View.VISIBLE);
					tab2.startAnimation(showAction);
				}
			}
		});
		if (!isDeleteMode) {
			tab1.setVisibility(View.GONE);
			tab2.setVisibility(View.VISIBLE);
			tab2.startAnimation(hiddenAction);
		} else {
			tab2.setVisibility(View.GONE);
			tab1.setVisibility(View.VISIBLE);
			tab1.startAnimation(hiddenAction);
		}

	}

	private void selete(boolean isSelected) {
		countMoney = 0;
		if (isSelected) {
			selectCount = 0;
			goodCount = 0;
		}
		for (ShoppingCartData data : verticalListData) {
			data.setCheck(isSelected);
			if (isSelected) {
				if (selectCount < verticalListData.size()) {
					selectCount++;
					goodCount += data.getCount();
					countMoney += data.getPrice() * data.getCount();
				}
			} else {
				if (selectCount > 0) {
					goodCount -= data.getCount();
					selectCount--;
				}
			}
		}
		if (!isDeleteMode) {
			countTextView.setText("(" + goodCount + "件)");
			countMoneyTextView.setText("¥"
					+ SystemTools.roundString(countMoney, 2));
		}
	}

	private void getCartlist() {
		if (isLogin(true)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.cartlist + "&password="
							+ userData.getUserpassword() + "&userphone="
							+ userData.getUserphone(),
					new MyRequestCallBack<String>(ShoppingCart.this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
							scrollView.onRefreshComplete();
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								verticalListData.clear();
								horizontalListDara.clear();
								if (state == 1) {
									JSONObject info = json
											.getJSONObject("info");
									JSONArray carlist = info
											.getJSONArray("carlist");
									goodCount = 0;
									countMoney = 0;
									selectCount = 0;

									for (int i = 0; i < carlist.length(); i++) {
										JSONObject carlistItem = carlist
												.getJSONObject(i);
										ShoppingCartData data = JsonHelper
												.parseObject(carlistItem,
														ShoppingCartData.class);
										data.setCheck(true);
										selectCount++;
										goodCount += data.getCount();
										countMoney += data.getPrice()
												* data.getCount();
										verticalListData.add(data);

									}
									allSelectButton.setSelected(true);
									countTextView.setText("(" + goodCount
											+ "件)");
									countMoneyTextView.setText("¥"
											+ SystemTools.roundString(
													countMoney, 2));
									JSONArray relate = info
											.getJSONArray("relate");
									for (int i = 0; i < relate.length(); i++) {
										JSONObject relateItem = relate
												.getJSONObject(i);
										RelatedData data2 = JsonHelper
												.parseObject(relateItem,
														RelatedData.class);
										horizontalListDara.add(data2);
									}

								} else if (state == 0) {

								} else if (state == -100) {
									passwordIsError(true);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
							if (verticalListData.size() == 0) {
								listViewForScrollView.setVisibility(View.GONE);
								findViewById(R.id.gwc_no).setVisibility(
										View.VISIBLE);
							} else {
								listViewForScrollView
										.setVisibility(View.VISIBLE);
								findViewById(R.id.gwc_no).setVisibility(
										View.GONE);
							}
							verticalAdapter.notifyDataSetChanged();
							horizontalAdapter.notifyDataSetChanged();
							scrollView.onRefreshComplete();
						}
					});
		}

	}

	private class MyAdapterHorizontal extends BaseAdapter {
		@Override
		public int getCount() {
			return horizontalListDara.size();
		}

		@Override
		public Object getItem(int position) {
			return horizontalListDara.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			final RelatedData data = horizontalListDara.get(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.shoppingcart_horizontal_list_item, null);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.image);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.price = (TextView) convertView.findViewById(R.id.price);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			bitmapUtils.display(holder.imageView,
					SystemTools.getHttpFileUrl(data.getImg()));
			holder.name.setText(data.getGoodsname());
			holder.price.setText("¥"
					+ SystemTools.roundString(data.getPrice(), 2));
			return convertView;
		}

		private class ViewHolder {
			ImageView imageView = null;
			TextView name = null;
			TextView price = null;
		}
	}

	private class MyAdapterVertical extends BaseAdapter {

		@Override
		public int getCount() {
			return verticalListData.size();
		}

		@Override
		public Object getItem(int position) {
			return verticalListData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			final ShoppingCartData data = verticalListData.get(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.item_shoppingcart, null);
				holder.checkBox = (Button) convertView
						.findViewById(R.id.select);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.image);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.price = (TextView) convertView.findViewById(R.id.price);
				holder.num = (NumberSelectView) convertView
						.findViewById(R.id.num);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ShoppingCart.this,
							ProductDetail.class);
					intent.putExtra("id", data.getGoodsid());
					startActivity(intent);
				}
			});
			holder.checkBox.setSelected(data.isCheck());
			holder.checkBox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					v.setSelected(!v.isSelected());
					boolean isSelect = v.isSelected();
					data.setCheck(isSelect);
					if (isSelect) {
						if (selectCount < verticalListData.size()) {
							selectCount++;
							goodCount += data.getCount();
							countMoney += data.getPrice() * data.getCount();
						}
					} else {
						if (selectCount > 0) {
							selectCount--;
							goodCount -= data.getCount();
							countMoney -= data.getPrice() * data.getCount();
						}
					}
					if (selectCount >= verticalListData.size()) {
						selectCount = verticalListData.size();
						allSelectButton.setSelected(true);
					} else {
						allSelectButton.setSelected(false);
					}
					if (!isDeleteMode) {
						countTextView.setText("(" + goodCount + "件)");
						countMoneyTextView.setText("¥"
								+ SystemTools.roundString(countMoney, 2));
					}
				}
			});
			bitmapUtils.display(holder.imageView,
					SystemTools.getHttpFileUrl(data.getImg()));
			holder.name.setText(data.getGoodsname());
			holder.price.setText("¥"
					+ SystemTools.roundString(data.getPrice(), 2));
			holder.num.setNumber(data.getCount());
			holder.num.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onSubClick(int num, NumberSelectView view) {
					updatecar(data, 2, view);
				}

				@Override
				public void onAddClick(int num, NumberSelectView view) {
					updatecar(data, 1, view);

				}
			});
			return convertView;
		}

		private class ViewHolder {
			Button checkBox;
			ImageView imageView = null;
			TextView name = null;
			TextView price = null;
			NumberSelectView num;
		}
	}

	/*
	 * 9.修改商品数量
	 */
	private void updatecar(final ShoppingCartData data, int type,
			final NumberSelectView num) {
		if (isLogin(true)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.updatecar + "&password="
							+ userData.getUserpassword() + "&userphone="
							+ userData.getUserphone() + "&type=" + type
							+ "&id=" + data.getGoodsid(),
					new MyRequestCallBack<String>(ShoppingCart.this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									int count = json.getInt("count");
									int addCount = count - data.getCount();
									num.setNumber(count);
									data.setCount(count);
									int spNum = MySharedPreferences
											.getSharedPreferencesKeyAndValue(
													ShoppingCart.this,
													MySharedPreferences.USER_DATA,
													"gouwucheNumber", 0);
									if (spNum == -1) {
										spNum = 0;
									}
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													ShoppingCart.this,
													MySharedPreferences.USER_DATA,
													"gouwucheNumber",

													spNum + addCount);
									setGouwucheNumber((TextView) findViewById(R.id.gwc_number));
									goodCount += addCount;
									countMoney += data.getPrice() * addCount;
									if (!isDeleteMode) {
										countTextView.setText("(" + goodCount
												+ "件)");
										countMoneyTextView.setText("¥"
												+ SystemTools.roundString(
														countMoney, 2));
									}

								}

								else if (state == -100) {
									passwordIsError(false);

								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	private void delete() {
		if (isLogin(true)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.deletebatch + "&password="
							+ userData.getUserpassword() + "&userphone="
							+ userData.getUserphone() + "&idval="
							+ getSeleteId(), new MyRequestCallBack<String>(
							ShoppingCart.this, getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									getCartlist();
								} else if (state == -100) {
									passwordIsError(false);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	private String getSeleteId() {
		// 遍历出id 2,4,6
		StringBuilder id = new StringBuilder();

		for (ShoppingCartData data : verticalListData) {
			if (data.isCheck()) {
				id.append(data.getGoodsid() + ",");

			}
		}
		if (id.length() > 0) {
			id.delete(id.length() - 1, id.length());
		}
		MyLog.e("getSeleteId", id.toString());
		return id.toString();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!isLogin(false)) {
			finish();
		}
		getCartlist();
		ShareMethod.setButton(ll_four, false);

	};

}
